package com.fenghongzhang.day012;

import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }


    public void test(View view) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL("http://www.baidu.com");
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                    //默认就是get
//                    connection.setRequestMethod("GET");
                    //请求时间
//                    connection.setReadTimeout(3*1000);
//                    connection.setConnectTimeout(3*1000);
                    //建立链接
//                    connection.connect();


                    if(connection.getResponseCode() == 200){
                        InputStream inputStream = connection.getInputStream();

                        StringBuilder stringBuilder = new StringBuilder();
                        //把一个流转换成文字
                        byte[] bytes =  new byte[1024];
                        int len =0;
                        while ((len = inputStream.read(bytes)) != -1){
                            String s = new String(bytes, 0, len);
                            stringBuilder.append(s);
                        }
                        String string = stringBuilder.toString();
                        Log.i(TAG, "test: "+string);
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();



    }
}
